package com.wang.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.application.api.userMenu.queryUserMenu.*;
import com.wang.application.api.userMenu.saveUserMenu.SaveUserMenuRequest;
import com.wang.application.mapper.DaMenuMapper;
import com.wang.application.mapper.DaUserMapper;
import com.wang.application.mapper.DaUserMenuMapper;
import com.wang.application.model.DaUser;
import com.wang.application.model.DaUserMenu;
import com.wang.application.service.DaUserMenuService;
import com.wang.common.common.AService;
import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import com.wang.common.model.RUser;
import com.wang.common.utils.Contact;
import com.wang.common.utils.MybatisUtil;
import com.wang.common.utils.RedisUtil;
import com.wang.common.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Mr.wang
* @description 针对表【da_user_menu(用户菜单表)】的数据库操作Service实现
* @createDate 2022-11-02 10:01:25
*/
@Service
@Slf4j
public class DaUserMenuServiceImpl extends ServiceImpl<DaUserMenuMapper, DaUserMenu>
    implements DaUserMenuService{

    @Resource
    private AService aService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private DaUserMenuMapper daUserMenuMapper;

    @Resource
    private DaMenuMapper daMenuMapper;

    @Resource
    private DaUserMapper daUserMapper;

    @Override
    public QueryUserMenuResponse queryUserMenu() {
        log.info("=========================queryUserMenu start");

        // 父级菜单查询
        Map<String, String> map = new HashMap<>();
        String token = aService.getReq().getHeader("token");
        RUser rUser = (RUser) Utils.jsonStringToObj(redisUtil.getString(token), RUser.class);
        String userId = rUser.getUserid();
        map.put("userid", userId);
        QueryUserMenuResponse queryUserMenuResponse = new QueryUserMenuResponse();
        List<MenuFatherList> daMenus;
        try {
            daMenus = daMenuMapper.selectFatherMenu(map);
            for (MenuFatherList daMenu : daMenus) {
                Map<String, String> ma = new HashMap<>();
                ma.put("userid", userId);
                ma.put("fatherid", daMenu.getMenuid());
                List<UserMenuList> userMenuLists = daMenuMapper.selectUserMenu(ma);
                daMenu.setUserMenuLists(userMenuLists);
                for (UserMenuList userMenuList : userMenuLists) {
                    Map<String, String> m = new HashMap<>();
                    m.put("userid", userId);
                    m.put("fatherid", userMenuList.getMenuid());
                    List<LeftMenuList> leftMenuList = daMenuMapper.selectLeftMenu(m);
                    userMenuList.setLeftMenuLists(leftMenuList);
                }
            }
            queryUserMenuResponse.setMenuFatherLists(daMenus);
        } catch (Exception e) {
            log.error("用户菜单查询失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户菜单查询失败");
        }
        log.info("========================={}用户菜单：", userId);
        Utils.XMLParse(queryUserMenuResponse, QueryUserMenuResponse.class);
        return queryUserMenuResponse;
    }

    @Override
    public Page<AllUserList> queryAllUserMenu(QueryAllUserMenuRequest request) {
        log.info("\n=======================QueryAllUserMenuRequest:{}", request);

        // 1、权限校验
        aService.authValid();
        // 2、查询所有已激活用户信息
        QueryWrapper<DaUser> queryWrapper = new QueryWrapper<>();
        MybatisUtil.queryLikeFilter(queryWrapper, request.likeTransfer());
        if (request.getTimeRange() != null && request.getTimeRange().size() > 0) {
            queryWrapper.ge("createtime", request.getStarttime());
            queryWrapper.le("createtime", request.getEndtime());
        }
        if ("0".equals(request.getSort())) {
            queryWrapper.orderByDesc("userid");
        } else {
            queryWrapper.orderByAsc("userid");
        }
        Page<DaUser> page = new Page<>(request.getCurrent(), request.getSize());
        daUserMapper.selectPage(page, queryWrapper);
        // 3、转换对象
        Page<AllUserList> listPage = new Page<>();
        listPage.setCurrent(page.getCurrent());
        listPage.setSize(page.getSize());
        listPage.setTotal(page.getTotal());
        List<AllUserList> lists = new ArrayList<>();
        // 4、查询用户菜单
        for (DaUser record : page.getRecords()) {
            AllUserList allUserList = new AllUserList();
            allUserList.setUserid(record.getUserid());
            allUserList.setUsername(record.getUsername());
            allUserList.setNickname(record.getNickname());
            allUserList.setAuthid(record.getAuthid());
            allUserList.setCreatetime(record.getCreatetime());
            Map<String, String> map = new HashMap<>();
            map.put("userid", allUserList.getUserid());
            List<MenuFatherList> menuFatherLists = daMenuMapper.selectFatherMenu(map);
            for (MenuFatherList daMenu : menuFatherLists) {
                Map<String, String> ma = new HashMap<>();
                ma.put("userid", allUserList.getUserid());
                ma.put("fatherid", daMenu.getMenuid());
                List<UserMenuList> userMenuLists = daMenuMapper.selectUserMenu(ma);
                for (UserMenuList userMenuList : userMenuLists) {
                    Map<String, String> m = new HashMap<>();
                    m.put("userid", allUserList.getUserid());
                    m.put("fatherid", userMenuList.getMenuid());
                    List<LeftMenuList> leftMenuList = daMenuMapper.selectLeftMenu(m);
                    userMenuList.setLeftMenuLists(leftMenuList);
                }
                daMenu.setUserMenuLists(userMenuLists);
            }
            allUserList.setMenuFatherLists(menuFatherLists);
            lists.add(allUserList);
        }
        listPage.setRecords(lists);
        return listPage;
    }

    @Transactional
    @Override
    public Boolean saveUserMenu(SaveUserMenuRequest request) {
        log.info("\n=======================SaveUserMenuRequest:{}", request);

        // 1、权限校验
        aService.authValid();
        // 2、数据校验
        if (Utils.isEmpty(request.getUserid()) || request.getMenuidlists() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不能为空");
        }
        // 3、根据用户ID查询所有用户菜单
        QueryWrapper<DaUserMenu> userMenuQueryWrapper = new QueryWrapper<>();
        userMenuQueryWrapper.eq("userid", request.getUserid());
        List<DaUserMenu> daUserMenus = daUserMenuMapper.selectList(userMenuQueryWrapper);
        // 4、增加、删除
        List<String> list = request.getMenuidlists();
        try {
            for (DaUserMenu daUserMenu : daUserMenus) {
                if (!list.contains(daUserMenu.getMenuid())) {
                    // 列表里不存在已有菜单，删除
                    daUserMenuMapper.deleteById(daUserMenu.getUsermenuid());
                    continue;
                }
                // 列表里存在已有菜单，清除列表中此项
                list.remove(daUserMenu.getMenuid());
            }
            // 列表里存在没有的菜单，增加
            for (String menuid : list) {
                userMenuQueryWrapper = new QueryWrapper<>();
                userMenuQueryWrapper.orderByDesc("usermenuid").last("limit 1");
                DaUserMenu dum = daUserMenuMapper.selectOne(userMenuQueryWrapper);
                DaUserMenu daUserMenu = new DaUserMenu();
                daUserMenu.setUsermenuid(Utils.formatId(dum.getUsermenuid(), 10));//用户菜单id
                daUserMenu.setUserid(request.getUserid());//用户id
                daUserMenu.setMenuid(menuid);//菜单id
                daUserMenu.setStatus(Contact.Status.ACTIVE);//激活状态
                daUserMenuMapper.insert(daUserMenu);
            }
        } catch (Exception e) {
            log.error("保存用户菜单失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "保存用户菜单失败");
        }
        return true;
    }
}




